/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.service.merchant;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.persistence.Parameter;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryIndent;
import com.neusoft.lohas.modules.ivm.dao.merchant.DeliveryIndentDao;

/**
 * 送货员送货信息Service
 * @author Jackie.Liu
 * @version 2014-11-03
 */
@Component
@Transactional(readOnly = true)
public class DeliveryIndentService extends BaseService {

	@Autowired
	private DeliveryIndentDao deliveryIndentDao;
	
	public DeliveryIndent get(String id) {
		return deliveryIndentDao.get(id);
	}
	
	public Page<DeliveryIndent> findStat(Page<DeliveryIndent> page, DeliveryIndent deliveryIndent) {
		return null;
	}
	
	public Page<Map<String, Object>> findDeliveryAccess(Page<Map<String, Object>> page, String startDate, String endDate, String userId) {
		String sql = "SELECT i.member_id as memberId, m.name as memberName, m.phone as phone, count(DISTINCT (i.delivery_date)) as days, count(i.id) as totalIndents, ifNull(round(count(i.id) / count(DISTINCT (i.delivery_date))),0) as average "
			+ " FROM ivm_delivery_indent i,ivm_delivery_member m where i.member_id = m.id and m.create_by = :p1";
		if("".equals(startDate) && "".equals(endDate)){
			sql += " group by i.member_id";
			return deliveryIndentDao.findBySql(page, sql, new Parameter(userId), Map.class);
		}else if("".equals(startDate) && !"".equals(endDate)){
			sql += " and i.delivery_date<=:p2 group by i.member_id";
			return deliveryIndentDao.findBySql(page, sql, new Parameter(userId, endDate), Map.class);
		}else if(!"".equals(startDate) && "".equals(endDate)){
			sql += " and i.delivery_date>=:p2 group by i.member_id";
			return deliveryIndentDao.findBySql(page, sql, new Parameter(userId, startDate), Map.class);
		}else{
			sql += " and i.delivery_date between :p2 and :p3 group by i.member_id";
			return deliveryIndentDao.findBySql(page, sql, new Parameter(userId, startDate, endDate), Map.class);
		}
		
	}
	
	@Transactional(readOnly = false)
	public void save(DeliveryIndent deliveryIndent) {
		deliveryIndentDao.save(deliveryIndent);
	}
	
	@Transactional(readOnly = false)
	public void save(List<DeliveryIndent> list) {
		deliveryIndentDao.clear();
		deliveryIndentDao.save(list);
	}

	public DeliveryIndent findByOrderId(String orderId) {
		DeliveryIndent deliveryIndent = new DeliveryIndent();
		deliveryIndent = deliveryIndentDao.findByOrderId(orderId);
		return deliveryIndent;
	}
	
	@Transactional(readOnly = false)
	public int deleteIndentById(String id){
		return deliveryIndentDao.deleteIndentById(id);
	}
	
}
